/*
 * 显示办税地图的Activity<br>
 * 界面中显示各个分局的列表，点击后跳转到显示详细内容的Activity<br>
 */
package com.taxsystem.chengwenzhi.branch_map;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.main.taxsystem.R;
import com.main.taxsystem.TableInfoSet.BranchMapTableInfo;
import com.main.taxsystem.TaxSystemContentProvider;
import com.taxsystem.tool.CommonOperations;
import com.taxsystem.tool.HttpUtil;

public class BranchMapActivity extends Activity implements
LoaderManager.LoaderCallbacks<Cursor>{
	private static final String TAG = "BranchMap";
	private static final String 
	ACTION = "com.taxsystem.chengwenzhi.branch_map.HTTP_GET_FINISH";
	private static final String PARAMETER ="/app/branch/branchgilist";
	private static final Void Void = null;
	private ProgressBar loadingIcon = null;
	private ListView listView = null;
	private SimpleCursorAdapter adapter = null;
	private static String HOST	= null;
	private MyThread myThread = null;
	private LocalBroadcastManager lbm = null;
	private String url = null;
	private Cursor cursor = null;
	private Handler handler = null;
	private static final int NETWORK_CONNECT_FAIL = 1;
	private static final int HTTP_OK = 200;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.branch_map);
		HOST = getResources().getString(R.string.host);
		url = HOST + PARAMETER;
		
		ActionBar bar = getActionBar();
        bar.setHomeButtonEnabled(true);
        bar.setIcon(R.drawable.actionbar_icon);
        bar.setDisplayHomeAsUpEnabled(true);
        bar.setBackgroundDrawable(new ColorDrawable(0xff34a4f7));
        
		setProgressBarIndeterminateVisibility(true);//show ProgressBar on ActionBar
		getLoaderManager().restartLoader(0, null, this);
		
		listView = (ListView) this.findViewById(R.id.branch_list);
		
		adapter = new SimpleCursorAdapter(
				this, 
				R.layout.branch_map_list_item,
				cursor,
				new String[]{
						BranchMapTableInfo.COLUMN_NAME_BRANCH_NAME,
						BranchMapTableInfo.COLUMN_NAME_ADDRESS,
						BranchMapTableInfo.COLUMN_NAME_DISTANCE},
				new int[]{
						R.id.branch_name,
						R.id.branch_address,
						R.id.branch_distance},
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnListItemClickListener());
		
		handler = new MyHandler(BranchMapActivity.this.getMainLooper());
		
			myThread = new MyThread();
			myThread.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		return true;
	}
	
	public void addListItem(List<HashMap<String,String>> list){
		list.addAll(list);
		adapter.notifyDataSetChanged();
		return;
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Log.v(TAG, "onCreateLoader() begin ,");
		CursorLoader loader = new CursorLoader(this,
				TaxSystemContentProvider.URI_BRANCH_MAP, null, null,
				null, null);
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if (cursor.getCount() < 1) {
			Log.v(TAG, "onCreateLoader() cursor.getCount() < 1, return");
			return;
		}
		this.cursor = cursor;
		cursor.setNotificationUri(getContentResolver(), TaxSystemContentProvider.URI_BRANCH_MAP);
		adapter.swapCursor(cursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		adapter.swapCursor(null);
	}
	
	private class OnListItemClickListener implements OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			Intent intent = new Intent(BranchMapActivity.this,MapDetailActivity.class);
			cursor.moveToPosition(position);
			intent.putExtra("branchId", 
					cursor.getString(cursor.getColumnIndex(BranchMapTableInfo.COLUMN_NAME_BRANCH_ID)));
			startActivity(intent);
		}
	}
	
	private class MyThread extends Thread {
		private static final int MAX_REQUEST_TIME = 3;
		
		@Override
		public void run() {
			Log.v(TAG, "MyThread.run()");
			if(false == CommonOperations.isNetworkConnected(BranchMapActivity.this))
				sendNetworkConnectFailMessage();
			String result = null;
			for(int i=0;i<MAX_REQUEST_TIME;++i){
				Log.v(TAG,"GetNoticeFromInternetThread:"+(i+1)+"# 网络请求:url="+url);
				try {
					result = HttpUtil.getRequest(url);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				if(result!=null)
					break;
			}
			
			Log.v(TAG, "get data from HttpUtil:" + result);
			if(null == result){
				sendNetworkConnectFailMessage();
				return;
			}else{
				Message msg = handler.obtainMessage();
				handler.sendEmptyMessage(HTTP_OK);
			}
			 parseJSON(result);
		}
		
		private void sendNetworkConnectFailMessage(){
			Message msg = handler.obtainMessage();
			Bundle data = new Bundle();
			data.putInt("messageType",NETWORK_CONNECT_FAIL);
			msg.setData(data);
			handler.sendMessage(msg);
		}
		
		private void parseJSON(String jsonString){
			Log.v(TAG,"MyThread:parseJSON()");
			if (jsonString == null) {
				Log.e(TAG, "MyRecive.onReceive():jsonString is null");
				return;
			}
			
			ContentValues values= null;
			try {
				JSONObject jsonObject = new JSONObject(jsonString);
				JSONArray branchArray = jsonObject.getJSONArray("data");
				for(int i=0;i<branchArray.length() && !branchArray.isNull(i);++i){
					values = new ContentValues();
					JSONObject object = branchArray.getJSONObject(i);
					String id = object.getString("branchId");
					String name = object.getString("branchName");
					String address = object.getString("address");
					String longitude = object.getString("longitude");
					String latitude = object.getString("latitude");
					values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_ID, id);
					values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_NAME, name);
					values.put(BranchMapTableInfo.COLUMN_NAME_ADDRESS, address);
					values.put(BranchMapTableInfo.COLUMN_NAME_LONGITUDE, longitude);
					values.put(BranchMapTableInfo.COLUMN_NAME_LATITUDE, latitude);
					values.put(BranchMapTableInfo.COLUMN_NAME_DISTANCE, (214*(i+1))+"米");
					Log.v(TAG,values.toString());
					addIfNotExist(values);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} finally {
			}
		}
		
		private void addIfNotExist(ContentValues values){
			Log.v(TAG,"addIfNotExist()");
			
			String branchId = values.getAsString(BranchMapTableInfo.COLUMN_NAME_BRANCH_ID);
			ContentResolver cr  = getContentResolver();
			Cursor result = cr.query(TaxSystemContentProvider.URI_BRANCH_MAP, 
									new String[]{BranchMapTableInfo.COLUMN_NAME_BRANCH_ID},
									BranchMapTableInfo.COLUMN_NAME_BRANCH_ID+"='"+branchId+"'",
									null, null);
			if(result.getCount()>0){
				Log.v(TAG,"notice "+branchId + " has existed");
				return;//the notice is existed, should not be inserted into database
			}
			Log.v(TAG,"addIfNotExist():add values:"+values.toString());
			cr.insert(TaxSystemContentProvider.URI_BRANCH_MAP, values);
		}
	}
	
	private class MyHandler extends Handler{
		public MyHandler(Looper looper){
			super(looper);
		}
		
		
		@Override
		public void handleMessage(Message msg) {
			Log.v(TAG,"MyHandler:handleMessage()");
			Bundle b = msg.getData();
			switch(b.getInt("messageType")){
			case NETWORK_CONNECT_FAIL:{
				Toast.makeText(BranchMapActivity.this,
						getResources().getString(R.string.network_connect_fail_hint), 
						Toast.LENGTH_SHORT).show();
				break;
			}
			}
			BranchMapActivity.this.setProgressBarIndeterminateVisibility(false);
		}
	}
}
